<?php

/**
 * 夏日葵电商系统
 * http://www.xiarikui.com
 */

namespace Xcx\Controller;

class PaymentController extends XcxBaseController {

    public $payment; //  具体的支付类
    public $pay_code; //  具体的支付code

    /**
     * 初始化
     */
    public function __construct() {
        parent::__construct();

        /*if (!in_array(ACTION_NAME, array('login'))) {
            $token = I('token', 0);
            $user_id = decrypt_token($token);
            if ($user_id == 0) {
                jsonReturn(-1, '参数错误1');
            }
            $this->user_id = $user_id;
        }*/

        //$this->pay_code = I('post.pay_code');
        $this->pay_code = 'weixin';
        include_once "plugins/payment/{$this->pay_code}/{$this->pay_code}.class.php";
        $code = '\\' . $this->pay_code; // \weixin
        $this->payment = new $code();
    }

    public function pay(){
        if (!$this->user_id) {
            jsonReturn(false, '获取不到当前用户信息');
        }
        if(!$this->user['openid']){
            jsonReturn(false, '当前用户缺少支付参数');
        }
        $question_id = I('post.question_id');
        $type = I('post.type');
        $from = I('post.from');
        $this->getWeiXinPayConfig($question_id,$type,$from);

    }


    public function  payment_after(){
        $sign = I('get.sign');
        $msg = I('get.msg');
    }

    /**
     * 支付配置
     */
    public function payConfig() {
        $order_id = I('post.order_id', 0); // 订单id
        if ($order_id == 0) {
            jsonReturn(-1, '参数错误3');
        }
        // 修改订单的支付方式
        $order = D('order')->where("order_id = $order_id")->find();
        //微信JS支付
        if ($this->pay_code == 'weixin') {
            $code_str = $this->payment->get_code($order, $config_value);
            jsonReturn(1, 'OK', $code_str);
        } elseif ($this->pay_code == 'usermoney') {
            $user_id = $this->user_id;
            $user_money = M('users')->where("user_id = {$user_id}")->getField('user_money');
            if ($order['total_amount'] <= $user_money) {
                $order_data['user_money'] = $order['total_amount'];
                $order_data['customer_status'] = 2;
                $order_data['seller_status'] = 1;
                $res = D('order')->where(array('order_id' => $order_id))->save($order_data);
                if (!$res) {
                    $res1 = orderRemark($order_id, $user_id, $order['seller_id'], 2, '请耐心等待商家确认');
                    $res2 = userLog($user_id, -$order['total_amount'], 0, '消费', $order_id, $order['order_sn']);
                    jsonReturn(1, '支付成功');
                } else {
                    jsonReturn(-1, '支付失败');
                }
            } else {
                jsonReturn(-1, '余额不足');
            }
        } else {
            $code_str = $this->payment->get_code($order, $config_value);
            jsonReturn(1, 'OK', $code_str);
        }
    }

    /**
     * 微信预支付接口
     */
    public function getWeiXinPayConfig($question_id,$type,$from) {
        //微信JS支付
        //1悬赏2打赏3付费查看

        if($type == 1) {

            $question = M('question')->where('id = ' . $question_id)->find();
            if (!$question) {
                jsonReturn(0, '查找不到此问题记录');
            }
            if ($question['open_reward'] != 1) {
                jsonReturn(0, '此问题并未开启悬赏');
            }
            if ($question['question_status'] != 1) {
                jsonReturn(0, '此问题状态并不需要悬赏');
            }
            $accountant_id = M('question_answer')->where('question_id = '.$question_id)->getField('answer_id');
            $money = $question['reward_money'];

        }elseif($type == 2) {
            $answer = M('answer')->where('question_id = ' . $question_id)->find();
            if (!$answer) {
                jsonReturn(0, '此问题仍未作答，无法打赏');
            }
            $money = I('post.money');
            if ((float)$money <= 0) {
                jsonReturn(0, '请填入正确的打赏金额');
            }
            $accountant_id = $answer['accountant_id'];

        }elseif($type == 3) {

            $answer = M('answer')->where('question_id = ' . $question_id)->find();
            if (!$answer) {
                jsonReturn(0, '此问题仍未作答，无法付费查看');
            }
            if ($answer['charge_view'] != 1) {
                jsonReturn(0, '此回答并未开启付费查看');
            }
            $accountant_id = $answer['accountant_id'];
            $money = $answer['charge_money'];

        }
        if (!$accountant_id){
            jsonReturn(0, '查找不到会计师信息');
        }

        $order['product_id'] =  $question_id;
        $order['attach'] =  json_encode(array(
            'question_id'=> $question_id ,
            'user_id' => $this->user_id,
            'accountant_id' => $accountant_id,
            'type' => $type,
            'from' => $from,
        ));
        $order['order_sn'] =  date('YmdHis').$question_id;
        $order['order_amount'] =  (float)$money;
        if ($this->pay_code == 'weixin') {

            $code_rs = $this->payment->getJSAPI($order, 1, $this->user['openid']);
            jsonReturn($code_rs);
        } else {

            $code_str = $this->payment->get_code($order);
            exit($code_str);
        }
    }

    /**
     * xiarikui 提交支付方式
     */
    public function getCode() {
//        C('TOKEN_ON', false); // 关闭 TOKEN_ON
        header("Content-type:text/html;charset=utf-8");
        $order_id = I('order_id'); // 订单id
        // 修改订单的支付方式
        $order = D('order')->where("order_id = $order_id")->find();
        if ($order['pay_status'] == 1) {
            jsonReturn(1, '此订单，已完成支付!');
        }

        $payment_arr = M('Plugin')->where("`type` = 'payment'")->getField("code,name");
        M('order')->where("order_id = $order_id")->save(array('pay_code' => $this->pay_code, 'pay_name' => $payment_arr[$this->pay_code]));
        if ($order['advance'] > 0 && $order['is_advance'] == 0) {
            $order['order_amount'] = $order['advance']; //先付预付款
        }
        if ($order['advance'] > 0 && $order['is_advance'] == 1) {
            $order['order_amount'] = $order['order_amount'] - $order['advance']; //再付尾款
        }

        jsonReturn(1, 'OK', $order);
// xiarikui 订单支付提交
//        $pay_radio = $_REQUEST['pay_radio'];
//        $config_value = parse_url_param($pay_radio); // 类似于 pay_code=alipay&bank_code=CCB-DEBIT 参数
////微信JS支付
//        if ($this->pay_code == 'weixin' && $_SESSION['openid'] && strstr($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')) {
//            $code_str = $this->payment->getJSAPI($order);
//            jsonReturn(1, 'OK', $code_str);
////            exit($code_str);
//        } else {
//            $code_str = $this->payment->get_code($order, $config_value);
//        }
//        $this->assign('code_str', $code_str);
//        $this->assign('order_id', $order_id);
//        $this->display('payment');  // 分跳转 和不 跳转 
    }

// 服务器点对点 // http://www.xiarikui.com/index.php/Home/Payment/notifyUrl        
    public function notify() {
        $this->payment->notify();
        exit();
    }

// 页面跳转 // http://www.xiarikui.com/index.php/Home/Payment/returnUrl        
    public function returnUrl() {
        $result = $this->payment->respond2(); // $result['order_sn'] = '201512241425288593';            
        if (stripos($result['order_sn'], 'recharge') !== false) {
            $order = M('recharge')->where("order_sn = '{$result['order_sn']}'")->find();
            $this->assign('order', $order);
            if ($result['status'] == 1)
                $this->display('rechargeSuccess');
            else
                $this->display('rechargeError');
            exit();
        }
        $order = M('order')->where("order_sn = '{$result['order_sn']}'")->find();
        $user = session('user');
        if ($order['user_id'] != $user['user_id']) {
            $this->error('参数错误');
        }
        $this->assign('order', $order);
        if ($result['status'] == 1)
            $this->display('success');
        else
            $this->display('error');
    }

    //手机端在线充值
    public function getPay() {
        C('TOKEN_ON', false); // 关闭 TOKEN_ON 
        header("Content-type:text/html;charset=utf-8");
        $order_id = I('order_id'); //订单id
        $user = session('user');
        $data['account'] = I('account');
        if ($order_id > 0) {
            M('recharge')->where(array('order_id' => $order_id, 'user_id' => $user['user_id']))->save($data);
        } else {
            $data['user_id'] = $user['user_id'];
            $data['nickname'] = $user['nickname'];
            $data['order_sn'] = 'recharge' . get_rand_str(10, 0, 1);
            $data['ctime'] = time();
            $order_id = M('recharge')->add($data);
        }
        if ($order_id) {
            $order = M('recharge')->where("order_id = $order_id")->find();
            if (is_array($order) && $order['pay_status'] == 0) {
                $order['order_amount'] = $order['account'];
                $pay_radio = $_REQUEST['pay_radio'];
                $config_value = parse_url_param($pay_radio); // 类似于 pay_code=alipay&bank_code=CCB-DEBIT 参数
                $payment_arr = M('Plugin')->where("`type` = 'payment'")->getField("code,name");
                M('recharge')->where("order_id = $order_id")->save(array('pay_code' => $this->pay_code, 'pay_name' => $payment_arr[$this->pay_code]));
                //微信JS支付
                if ($this->pay_code == 'weixin' && $_SESSION['openid'] && strstr($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')) {
                    $code_str = $this->payment->getJSAPI($order);
                    exit($code_str);
                } else {
                    $code_str = $this->payment->get_code($order, $config_value);
                }
            } else {
                $this->error('此充值订单，已完成支付!');
            }
        } else {
            $this->error('提交失败,参数有误!');
        }
        $this->assign('code_str', $code_str);
        $this->assign('order_id', $order_id);
        $this->display('recharge');
    }

}
